<template>
    <component :is="FormItem" ref="ObjItem" :Option="Option" v-model="InputValue" :DefaultValue="DefaultValue"
        :Model="ChildModel" :Level="ChildLevel" :Type="ChildType" />
</template>
<script setup>
import { shallowRef, ref, watch, inject } from 'vue'

import ItemString from './ItemString.vue';
import ItemNumber from './ItemNumber.vue';
import ItemSelect from './ItemSelect.vue';
import ObjectView from './ObjectView.vue';
import ArrayView from './ArrayView.vue';
import DictionaryView from './DictionaryView.vue';
const FormItemMapping = {
    String: ItemString,
    Number: ItemNumber,
    Select: ItemSelect,
    Model: ObjectView,
    Array: ArrayView,
    Dictionary: DictionaryView
}

const FormItem = shallowRef();
const InputValue = ref();
const emit = defineEmits(['UpdateValue'])
const props = defineProps(['Option', 'Model', 'Level', 'Value']);

const GetModel = inject('GetModel');

let DefaultValue = {};
let ChildModel = {};
let ChildLevel = props.Level + 1;
let ChildType = props.Option.ViewType;



async function InitModel() {
    var _TypeArray = props.Option.Type?.split(':') || [];
    var First = _TypeArray.shift();
    var _type = _TypeArray.join(':');
    switch (First) {
        case 'Model':
            ChildModel = await GetModel(_type);
            FormItem.value = FormItemMapping[First];
            break;
        case 'Array':
            FormItem.value = FormItemMapping[First];
            break;
        case 'Dictionary':
            FormItem.value = FormItemMapping[First];
            break;
        default:
            FormItem.value = FormItemMapping[props.Option.Type];
            break;
    }
}

InitModel();

watch(props.Value, () => {
    InputValue.value = props.Value[props.Option.Key];
}, { deep: true, immediate: true })

watch(InputValue, (val) => {
    emit('UpdateValue', props.Option.Key, val);
})

const ObjItem = ref();

defineExpose({
    ObjItem,
    Key: props.Option.Key
})


</script>
<style lang="less" scoped>

</style>